import { constantRoutes } from '@/router'
import Layout from '@/layout'
import { listToTreeList } from '@/utils/buildTree'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes (routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes ({ commit }, resources) {
    return new Promise(resolve => {
      let accessedRoutes = getRouter(resources)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

//将传入的resources转化为可注册routes的树状结构
function getRouter (resources) {
  let menus = [];
  for (let resource of resources) {
    if (state == 0) {
      continue
    }
    if (resource.id != resource.parentId) {
      menus.push({
        id: resource.id,
        path: `${resource.url}`,
        // component: resource.api == 'layout' ? Layout : () => import(`@/views/${resource.api}`),//会报错
        component: resource.api == 'layout' ? Layout : resolve => require([`@/views/${resource.api}`], resolve),
        name: `${resource.name}`,
        meta: { title: `${resource.name}`, icon: `${resource.closeIcon}`, openIcon: `${resource.openIcon}`, closeIcon: `${resource.closeIcon}` },
        parentId: resource.parentId
      })
    } else {
      menus.push({
        id: resource.id,
        path: `${resource.url}`,
        // component: resource.api == 'layout' ? Layout : () => import(`@/views/${resource.api}`),//会报错
        component: Layout,
        children: [{
          path: 'index',
          component: resolve => require([`@/views/${resource.api}`], resolve),
          meta: { title: `${resource.name}`, icon: `${resource.closeIcon}`, openIcon: `${resource.openIcon}`, closeIcon: `${resource.closeIcon}` },
        }]
      })
    }
  }
  //扁平数据树形话
  menus = listToTreeList(menus)
  // 动态添加404
  menus.push(
    {
      path: "/404",
      component: resolve => require(['@/views/404'], resolve),
      hidden: true,
    },
    {
      path: "*",
      redirect: "/404",
      hidden: true,
    }
  )
  return menus
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
